"""
Helper classes for parsers.
"""
import datetime
import decimal
import json
import uuid
from cy_query.db.models.query import QuerySet
from cy_query.utils.encoding import force_str
from cy_query.utils.functional import Promise
from cy_query.utils.date_time import DateTime


class JSONEncoder(json.JSONEncoder):
    """
    JSONEncoder subclass that knows how to encode date/time/timedelta,
    decimal types, generators and other basic python objects.
    """
    def default(self, obj):
        if isinstance(obj, Promise):
            return force_str(obj)
        elif isinstance(obj,(datetime.datetime,datetime.date,datetime.time,datetime.timedelta)):
            return DateTime(obj).to_string()
        elif DateTime and isinstance(obj,DateTime):
            return obj.to_string()
        elif isinstance(obj, decimal.Decimal):
            # Serializers will coerce decimals to strings by default.
            return float(obj)
        elif isinstance(obj, uuid.UUID):
            return str(obj)
        elif isinstance(obj, QuerySet):
            return tuple(obj)
        elif isinstance(obj, bytes):
            # Best-effort for binary blobs. See #4187.
            return obj.decode()
        elif hasattr(obj, 'tolist'):
            # Numpy arrays and array scalars.
            return obj.tolist()
        elif hasattr(obj, '__getitem__'):
            cls = (list if isinstance(obj, (list, tuple)) else dict)
            try:
                return cls(obj)
            except Exception:
                pass
        elif hasattr(obj, '__iter__'):
            return tuple(item for item in obj)
        return super().default(obj)
